<template>
  <div class="category-list">
    <div class="left-resize-bar">⋮</div>
    <el-scrollbar>
      <h2 class="first-menu">
        {{ firstMenu.title }}
      </h2>
      <div class="content-center">
        <router-link @click="stationContentRouterClick" to="/content/workStation">工作台</router-link>
      </div>
      <div @click="toggleShowContentManage" class="content-manage" :class="showContentManage ? '' : 'hide-line'">
        <span>内容管理</span>
        <i class="iconfont" :class="{ 'is-manage-expanded': showContentManage }">&#xe601;</i>
      </div>
      <el-collapse-transition>
        <div class="content-menu" v-show="showContentManage">
          <h2 @click="toggleShowCategoryTree">
            <div>
              <i class="iconfont" :class="{ 'is-expanded': showCategoryTree }">&#xe601;</i>
              <span>站点栏目</span>
            </div>
            <a href="javascript:;" class="manage-text" @click="toggleExpand">{{ expandTree ? '全部收起' : '全部展开' }}</a>
          </h2>
          <el-collapse-transition>
            <div class="second-menu" v-show="showCategoryTree">
              <el-tree
                class="category-tree"
                :data="categoryContentTreeData"
                :props="defaultProps"
                default-expand-all
                ref="categoryTree"
                node-key="id"
                @node-click="handleClickNode"
                v-loading="categoryTreeLoading"
                element-loading-background="rgba(242,242,242,0.8)"
              >
                <template #default="{ node, data }">
                  <div class="label-title">
                    <div class="category-icon-box" v-if="getAvatarUrl(data)">
                      <img class="icon" :src="getAvatarUrl(data)" alt="" />
                    </div>
                    <p :title="node.label">{{ node.label }}</p>
                    <el-dropdown class="more-icon-box">
                      <i class="iconfont more-icon">&#xe78d;</i>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <!-- <el-dropdown-item @click="noLimit(data)">管理</el-dropdown-item> -->
                          <el-dropdown-item v-if="data.type != 6" @click="handleStaticPreview(data)">静态预览</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </template>
              </el-tree>
            </div>
          </el-collapse-transition>
        </div>
      </el-collapse-transition>
      <!-- 显示其后路由 -->
      <HmsSidebarMenu :baseRoute="firstMenu.children.slice(2)" style="margin-top: 10px" />
    </el-scrollbar>
    <div class="my-content">
      <div class="my-content-top" @click="toggleExpandMyContent">
        <span>我的内容</span>
        <i class="iconfont" :class="{ 'is-expand': showMyContent }">&#xe601;</i>
      </div>
      <div class="my-content-contain" :class="{ 'is-expand': showMyContent }">
        <div class="inner-my-content">
          <router-link class="my-content-link" to="/content/my/release">我的发布</router-link>
          <router-link class="my-content-link" to="/content/my/collect">我的收藏</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
/* eslint-disable */
import { computed, ref, onMounted, reactive, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { getCategoryDetail } from '@/api/category'
import { ElMessage } from 'element-plus'
import { createTreeData, findParent } from '@ruifox-cms/utils'
import { myThrottle } from '@/utils/tools'

const store = useStore()
const router = useRouter()
const expandTree = ref(false)

const Menus = computed(() => {
  return store.getters.menus
})
const firstMenu = computed(() => {
  return findParent(Menus.value, router.currentRoute.value.meta.id)[0]
})
/*********************************************************************************************** */
const categoryContentTreeData = computed(() => {
  // return store.state.category.siteCategoryTree
  const permissionCategory = store.state.category.categoryFlat.filter(item => item.siteId === store.state.site.currentSite.id)
  const categoryTree = createTreeData(permissionCategory)
  return categoryTree
})
// 栏目树加载标志
const categoryTreeLoading = computed(() => {
  return store.state.content.categoryLoading
})
// 获取某个节点的所有子节点
const getNodesById = (nodes, id) => {
  const result = []
  for (const node of nodes) {
    if (node.pid === id) {
      result.push(node)
      const children = getNodesById(nodes, node.id)
      result.push(...children)
    }
  }
  return result
}
//搜索栏目
const categoryTree = ref()
const categorySpecialTree = ref()
const categoryDepartTree = ref()
const defaultProps = {
  children: 'children',
  label: 'name',
  class: function (data, node) {
    if (node.isLeaf) {
      return 'is-leaf'
    }
  }
}
const toggleExpand = () => {
  if (expandTree.value) {
    for (let key in categoryTree.value.store.nodesMap) {
      categoryTree.value.store.nodesMap[key].expanded = false
    }
    expandTree.value = !expandTree.value
  } else {
    for (let key in categoryTree.value.store.nodesMap) {
      categoryTree.value.store.nodesMap[key].expanded = true
    }
    expandTree.value = !expandTree.value
  }
}
// 添加栏目
const isShowAddCategory = ref(false)

const handleClickNode = (data, node) => {
  if (!node.isLeaf) return
  clearSideActiveStyle()
  router.replace({
    path: '/content/manage',
    query: {
      catId: data.id,
      modelId: data.modelId,
      type: data.type
    }
  })
}
const catList = ref([])
const catLoading = ref(false)
const handleCategoryDetail = id => {
  catList.value = []
  catLoading.value = true
  getCategoryDetail({ id: id }).then(res => {
    let _catList = res.data.call_other_id
    _catList = _catList.map(item => {
      return new Promise((resolve, reject) => {
        getCategoryDetail({ id: item })
          .then(res => {
            resolve(res)
          })
          .catch(() => {
            reject()
          })
      })
    })
    Promise.all(_catList).then(res => {
      res.forEach(item => {
        let _val = {
          name: item.data.name_path,
          modelId: item.data.model_id,
          catId: item.data.id,
          permission: item.data.permission,
          type: item.data.type
        }
        catList.value.push(_val)
      })
      catLoading.value = false
    })
  })
}
const showCallOther = data => {
  if (!catLoading.value) {
    handleCategoryDetail(data.id)
  }
}

router.beforeEach(async (to, from, next) => {
  if (to.query.catId) {
    setTimeout(() => {
      if (categoryTree.value) categoryTree.value.setCurrentKey(null)
      if (categoryDepartTree.value) categoryDepartTree.value.setCurrentKey(null)
      if (categorySpecialTree.value) categorySpecialTree.value.setCurrentKey(null)
      if (categoryTree.value) categoryTree.value.setCurrentKey(to.query.catId, true)
      if (categoryDepartTree.value) categoryDepartTree.value.setCurrentKey(to.query.catId, true)
      if (categorySpecialTree.value) categorySpecialTree.value.setCurrentKey(to.query.catId, true)
    }, 0)
    await store.dispatch('content/updateCategoryCrumb', to.query.catId)
    next()
  } else {
    setTimeout(() => {
      if (categoryTree.value) categoryTree.value.setCurrentKey(null)
      if (categoryDepartTree.value) categoryDepartTree.value.setCurrentKey(null)
      if (categorySpecialTree.value) categorySpecialTree.value.setCurrentKey(null)
    }, 0)
    next()
  }
})
onMounted(async () => {
  if (router.currentRoute.value.query.catId) {
    categoryTree.value.setCurrentKey(router.currentRoute.value.query.catId, true)
    store.dispatch('content/updateCategoryCrumb',router.currentRoute.value.query.catId)
  }
})
const showContentManage = ref(true)
const toggleShowContentManage = () => {
  showContentManage.value = !showContentManage.value
}
const showCommonTree = ref(false)
const toggleShowCommonTree = () => {
  showCommonTree.value = !showCommonTree.value
}
const showCategoryTree = ref(false)
const toggleShowCategoryTree = () => {
  showCategoryTree.value = !showCategoryTree.value
}
const showMyContent = ref(false)
const toggleExpandMyContent = () => {
  showMyContent.value = !showMyContent.value
}
const stationContentRouterClick = () => {
  clearSideActiveStyle()
}
const clearSideActiveStyle = () => {
  let curSide = document.querySelector('.sidebar-menu .is-current')
  if (curSide) curSide.classList.remove('is-current')
}
const getAvatarUrl = val => {
  if (val.icon) {
    return require(`@/assets/categoryIcon/${val.icon}.svg`)
  }
}

const isExpandLeft = ref(false)
let leftModuleWidth = ref(215 + 'px') //左侧模块宽度
const handleDragLeftResizeBar = () => {
  var leftResizeBar = document.getElementsByClassName('left-resize-bar')[0]
  var leftBox = document.getElementsByClassName('category-list')[0]
  // 鼠标按下事件
  leftResizeBar.onmousedown = function () {
    leftBox.style['transition'] = 'none'
    // 鼠标移动事件
    function moveBar(eventMove) {
      let width = eventMove.clientX
      if (width >= 900) {
        width = 900 // 设置最大拉伸宽度
      } else if (width <= 215) {
        width = 215
        isExpandLeft.value = true
      } else {
        isExpandLeft.value = false
      }
      leftModuleWidth.value = width + 'px'
    }
    let throttle = myThrottle(moveBar, 25)
    document.onmousemove = throttle
    // 鼠标松开事件
    document.onmouseup = function () {
      leftBox.style['transition'] = 'width 0.8s'
      // 颜色恢复
      document.onmousemove = null
      document.onmouseup = null
      leftResizeBar.releaseCapture && leftResizeBar.releaseCapture() // ReleaseCapture()函数用于释放该元素捕获的鼠标
    }
    leftResizeBar.setCapture && leftResizeBar.setCapture() // setCapture()函数用于设置该元素捕获的鼠标为空
    // 说明：一般情况下，SetCapture()和ReleaseCapture()函数是成对使用的。在使用SetCapture()函数捕获鼠标之后，需要在适当的时候调用ReleaseCapture()函数释放鼠标，否则可能会导致鼠标失去响应或者其他异常情况
    return false
  }
}
const noLimit = () => {
  ElMessage({
    showClose: true,
    message: '暂无权限',
    type: 'warning'
  })
}
// 静态预览
const handleStaticPreview = data => {
  if (data.type == 5) {
    //链接
    window.open(data.link)
  } else if (data.type == 6) {
    //菜单分类
    return
  } else {
    let url = ''
    if (process.env.NODE_ENV == 'development') {
      url = process.env.VUE_APP_BASE_API + '/station' + store.state.site.currentSite?.uri + data.uri
    } else {
      url = store.state.base.groupSetting.baseUrl + '/station' + store.state.site.currentSite?.uri + data.uri
    }
    window.open(url)
  }
}
onMounted(() => {
  nextTick(() => {
    handleDragLeftResizeBar()
    setTimeout(() => {
      toggleShowCategoryTree()
    }, 300)
  })
})
</script>

<style scoped lang="scss">
.category-list {
  width: v-bind(leftModuleWidth);
  background-color: $backBase;
  border-right: 1px solid $weightBar;
  height: calc(100vh - 65px);
  padding-bottom: 30px;
  box-sizing: border-box;
  position: relative;
  flex-shrink: 0;
  .left-resize-bar {
    position: absolute;
    right: -8px;
    top: 0;
    display: flex;
    align-items: center;
    width: 7px;
    height: 100%;
    // background-color: rgb(255, 255, 255);
    cursor: col-resize;
    user-select: none;
    transition: all ease 0.3s;
    font-size: 20px;
    color: #40485c;
    z-index: 999;

    &:hover {
      color: #fff !important;
      background-color: $mainColor !important;
    }
  }
  .iconfont {
    font-size: 12px;
  }
  .first-menu {
    font-size: 16px;
    font-weight: bold;
    padding: 25px 0 0 20px;
    margin-bottom: 20px;
    .iconfont {
      font-size: 18px;
      margin-right: 3px;
      font-weight: normal;
    }
  }
  .second-menu {
    .category-tree {
      padding: 0px 20px;
    }
    .operation-btn {
      display: flex;
      height: 30px;
      font-size: 12px;
      line-height: 30px;
      border: 1px solid #e4e4e4;
      text-align: center;
      justify-content: center;
      margin: 0 20px;
      color: var(--el-text-color-regular);
    }
  }
  h2 {
    font-size: var(--el-font-size-base);
    padding: 0 20px;
    // padding-bottom: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: normal;
    cursor: pointer;
    span {
      color: var(--el-text-color-regular);
      color: #333;
    }
    i {
      color: var(--el-text-color-regular);
      transition: all 0.3s;
      margin-right: 10px;
    }
    i.is-expanded {
      transform: rotate(180deg);
    }
    .manage-text {
      font-size: 12px;
      color: #aaa;
    }
  }
  // .bar{
  //   width: calc(100% - 20px);
  //   margin: 0 10px;
  //   height: 1px;
  //   background-color: #E4E4E4;
  // }
  .el-tree {
    background-color: inherit;
    .label-title {
      display: flex;
      align-items: center;
      .category-icon-box {
        width: 16px;
        height: 16px;
        margin-right: 3px;
        flex-shrink: 0;
        img {
          width: 100%;
          height: 100%;
        }
      }
      p {
        @include textEllipsis(16px, 1);
      }
      i {
        color: $mainColor;
        margin-left: 5px;
        font-size: 12px;
      }
      .more {
      }
    }
    ::v-deep(.el-tree-node__content) {
      padding: 8px 0;
      position: relative;
      .more-icon-box {
        position: absolute;
        top: 50%;
        right: 0;
        visibility: hidden;
        transform: translateY(-50%);
        .more-icon {
          font-size: 16px;
          font-weight: normal !important;
        }
      }

      &:hover {
        .more-icon {
          visibility: initial;
        }
      }
    }
    ::v-deep(.el-tree-node__content:hover) {
      background-color: rgba(0, 0, 0, 0.1);
    }
    ::v-deep(.el-tree-node.is-current) > .el-tree-node__content {
      color: #000;
    }
    ::v-deep(.el-tree-node.is-leaf.is-current) > .el-tree-node__content {
      color: $mainColor;
      font-weight: 600;
    }
  }
  .content-center {
    padding-top: 10px;
    // padding-left: 20px;
    margin-bottom: 20px;
    position: relative;
    a {
      font-size: 12px;
      font-weight: bold;
      color: #333;
      padding-left: 20px;
    }
    a.router-link-active {
      color: $mainColor;
    }
  }
  .my-content {
    position: absolute;
    bottom: 0;
    width: 100%;
    min-height: 30px;
    background-color: #fff;
    .my-content-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 30px;
      padding: 0 20px;
      box-shadow: 0px -5px 5px 0px rgba(0, 0, 0, 0.05);
      cursor: pointer;
      span {
        font-size: 12px;
        color: var(--el-text-color-regular);
      }
      i {
        color: var(--el-text-color-regular);
        margin-left: 20px;
        transition: all 0.3s;
        transform: rotate(180deg);
        &.is-expand {
          transform: rotate(0);
        }
      }
    }
    .my-content-contain {
      height: 0;
      transition: all 0.3s;
      overflow: hidden;
      &.is-expand {
        height: 80px;
      }
      .inner-my-content {
        padding: 10px 0;
        .my-content-link {
          display: block;
          padding: 0 20px;
          height: 30px;
          line-height: 30px;
          font-size: 12px;
          &.router-link-active {
            color: $mainColor;
          }
          &:hover {
            background-color: #f6f6f6;
          }
        }
      }
    }
  }
}
.category-item-box {
  min-height: 20px;
  .category-item {
    cursor: pointer;
  }
  .category-item + .category-item {
    margin-top: 10px;
  }
}
.custom-setting {
  .custom-setting-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.content-manage {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-sizing: border-box;
  cursor: pointer;
  position: relative;
  i {
    transition: 0.3s;
  }
  &::before {
    position: absolute;
    content: '';
    top: -12px;
    left: 50%;
    transform: translateX(-50%);
    width: 90%;
    height: 1px;
    background: rgba(170, 170, 170, 0.3);
  }
  span {
    color: #333333;
    font-weight: 700;
    font-size: 12px;
    line-height: 40px;
  }
  i {
    font-size: 16px !important;
    font-weight: 600;
    font-style: normal;
  }
}
// .hide-line{
//   position: relative;
//   &::after{
//     position: absolute;
//     content: "";
//     bottom: -6px;
//     left: 50%;
//     transform: translateX(-50%);
//     width: 90%;
//     height: 1px;
//     background: rgba(170, 170, 170, 0.3);
//   }
// }
.content-menu {
  position: relative;
  // &::after{
  //   position: absolute;
  //   content: "";
  //   bottom: -6px;
  //   left: 50%;
  //   transform: translateX(-50%);
  //   width: 90%;
  //   height: 1px;
  //   background: rgba(170, 170, 170, 0.3);
  // }
}
.is-manage-expanded {
  transform: rotate(180deg);
}
</style>
